package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import okhttp3.Request;
import org.bouncycastle.jcajce.provider.symmetric.AES;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 设备管理Service业务层处理
 * 
 * @author Jiagege
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        ListProductsRequest requeset = new ListProductsRequest();
        requeset.setLimit(50);
        ListProductsResponse response = client.listProducts(requeset);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("从物联网平台同步产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        String jsonStr = JSONUtil.toJsonStr(products);
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, jsonStr);
    }



    @Override
    public List<ProductVo> allProduct() {
        String jsonStr = redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST).toString();
        if (StringUtils.isBlank(jsonStr)) {
//            throw new BaseException("从物联网平台同步产品列表失败");
            return Collections.emptyList();
        }
        List<ProductVo> products = JSONUtil.toList(jsonStr, ProductVo.class);
        return products;
    }

    /**
     * 注册设备--------新增设备
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {

        long nameCount = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if (nameCount > 0) {
            throw new BaseException("设备名称已存在");
        }
        long nodeCount = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if (nodeCount > 0) {
            throw new BaseException("设备标识码已存在");
        }
        //判断同一位置是否绑定了相同产品
        long productCount = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType()));
        if (productCount > 0) {
            throw new BaseException("该位置已绑定相同产品");
        }


        AddDeviceRequest request =  new AddDeviceRequest();
        AddDevice body =  new AddDevice();
        body.setNodeId(dto.getNodeId());
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());
        AuthInfo authInfo =  new AuthInfo();
        String str = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.setSecret(str);
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("注册设备失败");
        }

        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(str);
        //todo
        device.setIotId(response.getDeviceId());
        this.save(device);

    }

    /**
     * 查询设备详情
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {

        //先查询本地数据库，若本地无数据，直接抛异常，不必联网查询IOT平台数据
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtils.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        //根据设备id  查询iot平台
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        //判断是否查询成功 非200均为不成功的情况
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备详情失败");
        }
        //数据封装
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //补充status和activeTime两个字段
        String deviceStatus = response.getStatus();
        String time = response.getActiveTime();

        vo.setDeviceStatus(deviceStatus);
        //此处进行格式转换，并且转为中国时区
        if(StringUtils.isNotEmpty(time)) {
            //处理时间字符串---带毫秒值
            LocalDateTime activeTimeStr = LocalDateTimeUtil.parse(time, DatePattern.UTC_MS_PATTERN);
            //转换时区至东八区
            LocalDateTime activeTime = DateTimeZoneConverter.utcToShanghai(activeTimeStr);
            vo.setActiveTime(activeTime);
        }
        return vo;
    }

    /**
     * 查询设备影子数据------设备上报的模型数据
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> getServiceInfo(String iotId) {
        List<Map<String, Object>> list = new ArrayList<>();
        ShowDeviceShadowRequest request =  new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);

        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("调用IOT平台获取数据失败！");
        }
        DeviceShadowData deviceShadowData = response.getShadow().get(0);

        //应用服务器可调用此接口查询指定设备的设备影子信息，包括对设备的期望属性信息（desired区）和设备最新上报的属性信息（reported区）。
        //所以此处调用reported，不调取desired

        DeviceShadowProperties reported = deviceShadowData.getReported();
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());

        String time = reported.getEventTime();
        //处理时间字符串---不带毫秒值
        LocalDateTime eventTimeStr = LocalDateTimeUtil.parse(time, "yyyyMMdd'T'HHmmss'Z'");
        //转换时区至东八区
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeStr);
        jsonObject.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return list;
    }

    @Override
    public void updateIotDevice(DeviceDto dto) {

        //修改IOTDA平台设备名称
        UpdateDeviceRequest request =  new UpdateDeviceRequest();
        UpdateDevice body =   new UpdateDevice();
        body.setDeviceName(dto.getDeviceName());
        request.setBody(body);
        request.setDeviceId(dto.getIotId());
        UpdateDeviceResponse response = client.updateDevice(request);
        //校验是否成功修改
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("修改IOTDA平台上设备信息失败！");
        }
        //修改本地存储的设备信息
        Device device = BeanUtil.toBean(dto, Device.class);

        /**
         * 不可以在同一个位置绑定同一个产品，这里指的是:
         *         若随身设备：路人甲-->路人乙，那么判断路人乙是否已经绑定此类型产品，
         *         若固定设备：查询是否已经绑定此类型产品，若有，则拒绝修改，不允许绑定
         */
        String remarkOld = deviceMapper.getRemark(dto.getId());
        String remarkNew = dto.getRemark();
        //若前后位置一致，则表示位置未发生修改，即无需进行判断是否绑定同类型产品，直接执行修改操作即可
        if(remarkOld.equals(remarkNew)) {
            this.updateById(device);
            return;
        }
        //若位置不一致，则位置发生变化，需要判断要修改到的位置是否已经绑定同类型产品，若数量大于0，最少为1，即已绑定，不予修改，反之可以修改
        long locationCount = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType()));
        if (locationCount > 0) {
            throw new BaseException("不可以在同一位置绑定相同类型的产品");
        }
        this.updateById(device);


    }

    /**
     * 删除设备
     * @param iotId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDeviceByIotId(String iotId) {

        DeleteDeviceRequest request =  new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode() != 204) {
            throw new BaseException("IOTDA平台删除设备失败");
        }
        //删除设备表中的数据
        deviceMapper.deleteDeviceByIotId(iotId);
        //删除设备数据表中的影子数据(属性数据)
        deviceMapper.deleteDeviceDataByIotId(iotId);


    }






    @Override
    public List<ServiceCapability> queryProduct(String productKey) {


        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
//        if(response.getHttpStatusCode()!=200){
//            return Collections.emptyList();
//        }
        List<ServiceCapability> list = response.getServiceCapabilities();
        if (ObjectUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        System.out.println("list = " + list);

        return list;
    }
}
